package Amavis::Custom;
use BerkeleyDB;
use strict;

BEGIN {
	import Amavis::Conf qw(:platform :confvars c cr ca $myhostname);
	import Amavis::Util qw(do_log untaint safe_encode safe_decode);
	import Amavis::rfc2821_2822_Tools;
	import Amavis::Notify qw(build_mime_entity);
}

sub new {
	my($class,$conn,$msginfo) = @_;
	my($self) = bless {}, $class;
	my $filename =
      "/var/list/.etc/dot-amavis/policybank.db";

	do_log(2, "CUSTOM: loaded lists.debian.org custom module");

	tie my %bank, 'BerkeleyDB::Btree',
	-Filename   => $filename,
	-Flags      => DB_CREATE
	    or die "Cannot open $filename: $! $BerkeleyDB::Error\n" ;


	foreach my $line (@{$msginfo->{'orig_header'}}) {
		$line =~ s/\n\t/ /g;
		if ($line =~ m/\(Postfix\) with E?SMTP id ([A-Z0-9]+)(;| for)/) {
			do_log(2, "original postfix id: $1, size: " . $msginfo->{'msg_size'});
		}
	}


	my $recipient = $msginfo->recips->[0];
	do_log(2, "CUSTOM: got recipient $recipient");
	

	my ($user, $domain) = split('@', $recipient);
	
	if (defined $bank{$recipient}) {
		Amavis::load_policy_bank("pb_" . $bank{$recipient});
		do_log(1, sprintf("Policy bank '%s' taken for recp '%s'",
				$bank{$recipient},
				$recipient));
	} elsif (defined $bank{$domain}) {
		Amavis::load_policy_bank($bank{$domain});
		do_log(1, sprintf("Policy bank '%s' taken for recp '%s'",
				$bank{$domain},
				$recipient));
	}
	return $self; 
}


sub after_send {  # may be left out if not needed
	my($self,$conn,$msginfo) = @_;
}

sub mail_done {  # may be left out if not needed
	my($self,$conn,$msginfo) = @_;
	if ($msginfo->{'recips'}->[0]->[13] =~ /queued as ([0-9A-Z]+)/) {
		do_log(2, "new postfix id: $1");
	}
}

	
1;  # insure a defined return

